//
//  CZAVAudioManager.m
//  translateAi
//
//  Created by 陈镇 on 2023/5/10.
//

#import "CZAVAudioManager.h"
#import <AVFoundation/AVFoundation.h>

#import "GTMBase64.h"
#import "SLUserPermissionsManager.h"
#import "WangYiReqManager.h"


static CZAVAudioManager *_manager = nil;
@interface CZAVAudioManager ()<AVAudioRecorderDelegate,AVAudioPlayerDelegate>

@property(nonatomic,weak) id<CZAVAudioManagerDelegate> delegate;
/** 注释*/
@property (nonatomic, strong) AVAudioRecorder * audioRecorder;
/** <#注释#>*/
@property (nonatomic, strong) AVAudioPlayer * player;
/** <#注释#>*/
@property (nonatomic, strong) AVPlayer * urlPlayer;
/** <#注释#>*/
@property (nonatomic, strong) NSTimer * timer;
/** 录音时长*/
@property (nonatomic, assign) CGFloat tiemlength;
/** 是否强制结束*/
@property (nonatomic, assign) BOOL isForceEnd;

@end
@implementation CZAVAudioManager

+(CZAVAudioManager *)shareManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [CZAVAudioManager new];
    });
    return _manager;
}

-(void)startRecordDelegate:(id<CZAVAudioManagerDelegate>)delegate{
    
    __weak typeof(self) weakSelf = self;
    [SLUserPermissionsManager isHaveAudioPermissionsBlock:^(BOOL isCan) {
        if(isCan){
            [weakSelf sl_startRecordDelegate:delegate];
        }
    }];
}

- (void)sl_startRecordDelegate:(id<CZAVAudioManagerDelegate>)delegate
{
    self.delegate = delegate;
    //删除上次生成的文件，保留最新文件
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //默认就是wav格式
    if ([fileManager fileExistsAtPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"recordAudio.wav"]]) {
        [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"recordAudio.wav"] error:nil];
        
    }
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord
                                     withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                           error:nil];
    
    //录音设置

    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

    //设置录音格式 AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];

    //设置录音采样率(Hz)
    [recordSetting setValue:[NSNumber numberWithFloat:16000] forKey:AVSampleRateKey];
//
//    //录音通道数 1
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
//
//    //线性采样位数 16
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];


    self.audioRecorder.meteringEnabled=YES;
    //设置录音时长，超过这个时间后，会暂停单位是秒
    [self.audioRecorder recordForDuration:30];
    
    NSString *urlString = [NSTemporaryDirectory()stringByAppendingPathComponent:@"recordAudio.wav"];
    //存储录音文件
    NSURL * recordUrl = [NSURL URLWithString:urlString];

    //初始化录音对象
    NSError * error;
    _audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:&error];

    if (error) {
        NSLog(@"%@",error.description);
        return;
    }
    _audioRecorder.delegate = self;
    
    //开启音量检测
    _audioRecorder.meteringEnabled = YES;
    
    //如果不是正在录音
    if (![_audioRecorder isRecording]) {

        [_audioRecorder prepareToRecord];//准备录音
        [_audioRecorder record];//开始录音
        [self timer];
    }
}
//结束录音
- (void)endRecord{
    //录音停止
    [_audioRecorder stop];
    [self endtimer];
}

-(void)abandonRecord{
    self.audioRecorder.delegate = nil;
    [self endRecord];
}
-(void)endtimer{
    [_timer invalidate];
    _timer = nil;
}
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    RTLog(@"录音回调结束 ------- %@",@(flag));
    [[AVAudioSession sharedInstance] setActive:NO error:nil];//一定要在录音停止以后再关闭音频会话管理（否则会报错），此时会延续后台音乐播放
    if (!flag) return;
    
//    [self playVoiceData:recorder.url];
    
    if(_tiemlength < 1000){
        if(_delegate && [_delegate respondsToSelector:@selector(audioRecorderUnderTime)]){
            [_delegate audioRecorderUnderTime];
        }
        _tiemlength = 0;
        return;
    }
    if(_delegate && [_delegate respondsToSelector:@selector(audioRecorderDidFinishvoiceBase64:isForceEnd:)]){
        
        NSData *voiceData = [NSData dataWithContentsOfFile:recorder.url.relativePath];
        
        NSString *voiceDataBase64 = [GTMBase64 stringByEncodingData:voiceData];
        
        [_delegate audioRecorderDidFinishvoiceBase64:voiceDataBase64 isForceEnd:_isForceEnd];
        _tiemlength = 0;
        _isForceEnd = NO;
    }
    
}

-(NSTimer *)timer{
    if(!_timer){
        @weakify(self)
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.001 block:^(NSTimer * _Nonnull timer) {
            @strongify(self)
            if(self.tiemlength > kMaxTimeLength * 1000){
                //超过20秒 就结束
                self.isForceEnd = YES;
                [self endRecord];
                return;
            }
            self.tiemlength ++;
        } repeats:YES];
    }
    return _timer;
}

- (void)playVoiceData:(NSData *)data delegate:(id<CZAVAudioManagerDelegate>)delegate{
    if(self.player && [self.player isPlaying]){
        [self.player stop];
    }
    self.delegate = delegate;
    NSError*error;

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                     withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                           error:nil];

    
    
    self.player = [[AVAudioPlayer alloc] initWithData:data error:&error];
    //设置播放循环次数
    [self.player setNumberOfLoops:0];
    [self.player setVolume:1];//音量，0-1之间
    //分配播放所需的资源，并将其加入内部播放队列
    [self.player setDelegate:self];
    [self.player prepareToPlay];
    [self.player play];

}
-(void)playVoiceURL:(NSString *)url delegate:(id<CZAVAudioManagerDelegate>)delegate{
    if(self.urlPlayer){
        [self.urlPlayer pause];
    }
    self.delegate = delegate;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                     withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                           error:nil];
    
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];

    self.urlPlayer = [[AVPlayer alloc] initWithPlayerItem:item];
    //设置播放循环次数
    [self.urlPlayer setVolume:1];//音量，0-1之间
    
    [self.urlPlayer play];
    
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endPlay) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([object isKindOfClass:[AVPlayerItem class]]) {
        if ([keyPath isEqualToString:@"status"]) {
            switch (((AVPlayerItem *)object).status) {
                case AVPlayerItemStatusReadyToPlay:{
                 
                    
                    NSString *speed = (NSString *)[[WangYiReqManager shareMangager].globalCache objectForKey:kVoiceSpeed];
                    if (speed.length == 0) {
                        self.urlPlayer.rate = 1;
                    }else{
                        if ([speed containsString:@"慢"]) {
                            self.urlPlayer.rate = 0.6;
                        }else  if ([speed containsString:@"快"]) {
                            self.urlPlayer.rate = 1.9;
                        } if ([speed containsString:@"正常"]) {
                            self.urlPlayer.rate = 1;
                        }
                    }
                    [self.urlPlayer play];
                    
                    if (speed.length == 0) {
                        self.urlPlayer.rate = 1;
                    }else{
                        if ([speed containsString:@"慢"]) {
                            self.urlPlayer.rate = 0.6;
                        }else  if ([speed containsString:@"快"]) {
                            self.urlPlayer.rate = 1.9;
                        } if ([speed containsString:@"正常"]) {
                            self.urlPlayer.rate = 1;
                        }
                    }
                }break;
                    
                case AVPlayerItemStatusUnknown:
                    NSLog(@"AVPlayerItemStatusUnknown");
                    break;
                    
                case AVPlayerItemStatusFailed:
                    NSLog(@"AVPlayerItemStatusFailed");
                    break;
                    
                default:
                    break;
            }
            
        }
    }
}

#pragma AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    if(_delegate && [_delegate respondsToSelector:@selector(auidoPlayDidFinishSuccess:)]){
        [_delegate auidoPlayDidFinishSuccess:YES];
    }
}

/* if an error occurs while decoding it will be reported to the delegate. */
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error{
    if(_delegate && [_delegate respondsToSelector:@selector(auidoPlayDidFinishSuccess:)]){
        [_delegate auidoPlayDidFinishSuccess:NO];
    }
}
-(void)endPlay{
    if(_delegate && [_delegate respondsToSelector:@selector(auidoPlayDidFinishSuccess:)]){
        [_delegate auidoPlayDidFinishSuccess:YES];
    }
}
@end
